package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.tbvtc.agriculturalcreditchainserver2025.dto.CouponDto.DeskillCouponDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.Coupon;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUserHolder;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CouponMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 优惠券主表 服务实现类
 * </p>
 *
 * @author syh
 * @since 2025-07-08
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String addDeskillCoupons(DeskillCouponDto deskillCouponDto) {
        Coupon coupon = BeanUtil.copyProperties(deskillCouponDto, Coupon.class);
        coupon.setCouponType(1);
        Snowflake snowflake = new Snowflake(1L, 1L); // workerId, da
        long id = snowflake.nextId();
        coupon.setId(String.valueOf(id));
        coupon.setFarmerId(LoginUserHolder.getLoginUser().getUserId());
        save(coupon);
        stringRedisTemplate.opsForValue().set(RedisConstant.COUPON_STOCK_KEY+coupon.getId(), coupon.getStock().toString());
        return coupon.getId();
    }
}
